package com.example.night.service.MysqlService;

import com.example.night.data.Influencer.InfluencerPackage;
import com.example.night.data.Influencer.InfluencerRepository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class InfluencerMysqlService {

    @Autowired
    private InfluencerRepository influencerRepository;

    @PersistenceContext
    private EntityManager entityManager;

    // 模拟从数据库或其他服务获取订单数据
    private List<Map<String, Object>> getOrderListForInfluencer(Long influencerId) {
        // 这里用模拟数据，实际应用可从订单表查询
        List<Map<String, Object>> orderList = new ArrayList<>();
        return orderList;
    }
    @Transactional
    public void creatTables(List<InfluencerPackage> influencerPackageLists) {
        for (InfluencerPackage influencerPackageList : influencerPackageLists) {
            String tableName = "orders_" + influencerPackageList.getPromoteId();
            String createTableSQL = "CREATE TABLE IF NOT EXISTS " + tableName + " ("
                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY, "
                    + "relate_order_no VARCHAR(255) NOT NULL UNIQUE, "  // 添加唯一约束
                    + "relate_product_id VARCHAR(255) NOT NULL, "
                    + "relate_product_name VARCHAR(255), "
                    + "relate_shop_name VARCHAR(255), "
                    + "order_pay_time DATETIME, "
                    + "order_confirm_time DATETIME, "
                    + "order_settle_time DATETIME, "
                    + "status INT, "
                    + "sys_settle_money DECIMAL(10,2), "
                    + "sys_relate_service_money_in DECIMAL(10,2), "
                    + "sys_relate_service_money_out DECIMAL(10,2) "
                    + ");";

            entityManager.createNativeQuery(createTableSQL).executeUpdate(); // 执行 SQL 创建表
        }
    }

    @Transactional
    public void saveInfluencers(List<InfluencerPackage> influencerPackageList) {
        if (influencerPackageList == null || influencerPackageList.isEmpty()) {
            return; // 如果列表为空，则直接返回
        }

        for (InfluencerPackage influencerPackage : influencerPackageList) {
            Optional<InfluencerPackage> existingInfluencer = Optional.ofNullable(influencerRepository.findByPromoteId(influencerPackage.getPromoteId()));

            if (existingInfluencer.isPresent()) {
                // 如果达人已存在，更新其数据
                InfluencerPackage dbInfluencerPackage = existingInfluencer.get();
                dbInfluencerPackage.setZfbId(influencerPackage.getZfbId());
                dbInfluencerPackage.setPromoteName(influencerPackage.getPromoteName());
                dbInfluencerPackage.setTotalGMV(influencerPackage.getTotalGMV());
                dbInfluencerPackage.setTotalOrders(influencerPackage.getTotalOrders());
                dbInfluencerPackage.setLeaderSysServiceMoney(influencerPackage.getLeaderSysServiceMoney());
                influencerRepository.save(dbInfluencerPackage); // 更新
            } else {
                // 如果达人不存在，则插入新数据
                influencerRepository.save(influencerPackage);
            }
        }
    }
    @Transactional
    public void saveInfluencersInfo(List<InfluencerPackage> influencerPackageList) {
        if (influencerPackageList == null || influencerPackageList.isEmpty()) {
            return; // 如果列表为空，则直接返回
        }

        List<InfluencerPackage> newInfluencerPackages = new ArrayList<>();

        for (InfluencerPackage influencerPackage : influencerPackageList) {
            Optional<InfluencerPackage> existingInfluencer = Optional.ofNullable(
                    influencerRepository.findByPromoteId(influencerPackage.getPromoteId())
            );
            String password = getPinyinInitials(influencerPackage.getName()) + "123456";
            if (existingInfluencer.isPresent()) {
                // 如果达人已存在，更新其手机号和密码
                InfluencerPackage dbInfluencerPackage = existingInfluencer.get();
                dbInfluencerPackage.setPhone(influencerPackage.getPhone());
                dbInfluencerPackage.setWxId(influencerPackage.getWxId());
                dbInfluencerPackage.setZfbId(influencerPackage.getZfbId());
                dbInfluencerPackage.setRoleType(influencerPackage.getRoleType());
                dbInfluencerPackage.setPassword(password);
                dbInfluencerPackage.setRegistered(true);
                dbInfluencerPackage.setName(influencerPackage.getName());
                influencerRepository.save(dbInfluencerPackage);
            } else {
                // 如果达人不存在，则初始化其余字段后插入新数据
                influencerPackage.setPassword(password);
                influencerPackage.setTotalGMV(0.0);
                influencerPackage.setTotalOrders(0);
                influencerPackage.setLeaderSysServiceMoney(0.0);
                influencerPackage.setTotalCommission(0.0);
                influencerPackage.setCoins(0);
                influencerPackage.setRegistered(true);
                influencerPackage.setPromoteName("");
                newInfluencerPackages.add(influencerPackage);
            }
        }

        if (!newInfluencerPackages.isEmpty()) {
            influencerRepository.saveAll(newInfluencerPackages); // 批量插入新达人
        }
    }

    public InfluencerPackage findInfluencerByPromoteId(String promoteId) {
        return influencerRepository.findByPromoteId(promoteId);
    }

    public List<InfluencerPackage> getAllRegisteredInfluencers() {
        return influencerRepository.findByIsRegisteredTrue();
    }
    public static String getPinyinInitials(String chinese) {
        StringBuilder initials = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
            if (pinyinArray != null) {
                initials.append(pinyinArray[0].charAt(0));
            }
        }
        return initials.toString().toUpperCase();
    }
}
